package org.wsff.tools.api.gateway.impl.spring;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.wsff.tools.api.gateway.error.GatewayException;
import org.wsff.tools.api.gateway.manager.Lifecycle;

import com.google.common.collect.Lists;

/**
 * ServletApiGatewayInitializer
 * @author ryan
 * @version Id: ServletApiGatewayInitializer.java, v 0.1 2022-04-01 16:36 ryan Exp $$
 */
@Service
public class ServletApiGatewayInitializer implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        SpringContextHolder.setApplicationContext(context);
        try {
            Map<String, Lifecycle> beansMap = context.getBeansOfType(Lifecycle.class, false, true);
            List<Lifecycle> beans = Lists.newArrayList(beansMap.values());
            Collections.sort(beans);
            for (Lifecycle item : beans) {
                item.start();
            }
        } catch (GatewayException e) {
            throw new IllegalArgumentException(e);
        }
    }

}
